package com.hnkywl.sts.action.sys;

import com.hnkywl.sts.dao.sys.PmDao;
import com.hnkywl.sts.entity.sys.Khjwh;
import com.hnkywl.sts.entity.sys.Pm;
import com.hnkywl.sts.service.sys.KhjwhService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.POIUtil;
import jxl.Sheet;
import jxl.Workbook;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.Region;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.hibernate.tool.hbm2x.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 说明：
 * 包:        com.hnkywl.sts.action.sfgl
 * 类描述:    控货价
 * 修改备注: [说明本次修改内容]
 * 版本:        [v1.0]
 */
@Namespace("/sys/khjwh")
public class KhjwhAction extends SimpleActionSupport {
    private KhjwhService khjwhService;
    private int page;
    //分页组件 页面大小
    private int rows = 10;
    private String sysDate;
    private PmDao pmDao;
    private File upload;
    private Date khjwhStartDate;
    private Date khjwhEndDate;
    private String pmName;
    private Long id;
    private String khj;

    @Action("khjwh")
    public String khjwh() {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        sysDate = simple.format(new Date());
        return SUCCESS;
    }

    // 控货价的查询分页显示
    @Action("khjwhList")
    public void khjwhList() {
        if (khjwhStartDate != null)
            khjwhStartDate = convertDate(khjwhStartDate, true);
        if (khjwhEndDate != null)
            khjwhEndDate = convertDate(khjwhEndDate, false);
        this.renderJson(this.khjwhService.findAllKhjwhList(pmName, khjwhStartDate, khjwhEndDate, page, rows));
    }

    @Action("save_khjwh")
    public void saveKhj() {
        try {
            if (khj.matches("[\\d.]+")) {
                Khjwh saveKhj = this.khjwhService.saveKhj(id, khj);
                renderJson("{\"statusCode\":200,\"品名：\":" + saveKhj.getPm().getJc() + "，修改成功" + "}");
            } else {
                renderJson("{\"statusCode\":300,\"message\":\"请输入数字！\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":300,\"message\":\"" + e.getMessage() + "\"}");
        }

    }

    // 导出品名信息
    @Action("khjwh_export")
    public String khjwh_export() {
        List<Map> pmList = pmDao.findAllPm(YgService.getCurrentYg().getZggs().getId());
        //第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("sheet1");
        POIUtil poiUtil = new POIUtil(wb);
        //设置列宽
        sheet.setDefaultRowHeightInPoints(15);
        sheet.setDefaultColumnWidth((short) 12);
        sheet.setColumnWidth((short) 0, (short) (20 * 512));
        sheet.setColumnWidth((short) 1, (short) (20 * 512));
        sheet.setColumnWidth((short) 2, (short) (20 * 512));
        //第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        row.setHeightInPoints(36);
        //第四步，创建单元格，并设置值表头  设置表头居中
        HSSFCellStyle titleStyle = poiUtil.createTitleHSSFCellStyle(wb);
        HSSFCell titleCell = row.createCell((short) 0);
        titleCell.setCellStyle(titleStyle);
        titleCell.setEncoding(HSSFCell.ENCODING_UTF_16);
        titleCell.setCellValue("控货价导入文件");
        sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) 2));
        //生成第一行数据...表头
        HSSFCellStyle headerStyle = poiUtil.createHeader3HSSFCellStyle(wb);
        poiUtil.fillRow(sheet, headerStyle, 1, "编码", "品名", "控货价");
        //生成从第二行开始的品名数据
        for (int i = 2; i < pmList.size() + 2; i++) { //从第三行开始导入
            poiUtil.fillRow(sheet, headerStyle, i, pmList.get(i - 2).get("CODE"), pmList.get(i - 2).get("NAME"), "");
        }
        try {
            response.setContentType("application/x-download");
            String filedisplay = new String(("控货价批量导入.xls").getBytes("gb2312"), "iso8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
            wb.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
            renderText("位置异常，导出失败" + e.getMessage());
        }
        return null;
    }

    // 控货价批量导入
    @Action("khjwh_import")
    public void khjwh_import() {
        try {
            // 导入数据
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
            Workbook book = Workbook.getWorkbook(upload);
            //  获得第一个工作表对象
            Sheet sheet = book.getSheet(0);
            //获取总行数
            int rows = sheet.getRows();
            List<Khjwh> khjList = new ArrayList<Khjwh>();
            for (int i = 2; i < rows; i++) { //从第三行开始导入
                Khjwh temp = new Khjwh();
                if (sheet.getCell(0, i) != null && StringUtils.isNotEmpty(sheet.getCell(0, i).getContents())) {//第一列 编码
                    Pm pm = pmDao.findByCode(sheet.getCell(0, i).getContents());
                    if (null == pm) {
                        renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "行没有查询品名信息！\"}");
                        return;
                    } else {
                        temp.setPm(pm);
                    }
                } else {
                    renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "行编码为空！\"}");
                    return;
                }
                Double jg;
                if (sheet.getCell(2, i) == null || StringUtils.isEmpty(sheet.getCell(2, i).getContents())) {
                    renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "控货价为空！\"}");
                    return;
                } else if (!sheet.getCell(2, i).getContents().matches("[\\d.]+")) {
                    renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "控货价不为数字！\"}");
                    return;
                } else {
                    jg = Double.parseDouble(sheet.getCell(2, i).getContents().toString());
                    temp.setKhj(jg);
                }
                temp.setDrrq(new Date());
                temp.setMj(YgService.getCurrentYg().getZggs());
                temp.setCreateUser(YgService.getCurrentYg());
                temp.setCreateOrgan(YgService.getCurrentYg().getZggs());
                temp.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                temp.setDateCreated(new Date());
                temp.setLastUpdated(new Date());
                khjList.add(temp);
            }
            khjwhService.saveOrUpdateKhj(khjList);
            renderText("{\"statusCode\":\"200\", \"message\":\"控货价批量导入成功！\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    /**
     * @param date
     * @param flag true:当天00:00:00   false:第二天00:00:00
     * @return
     */
    private Date convertDate(Date date, boolean flag) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        if (!flag)
            gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
        gc.set(GregorianCalendar.HOUR, 0);
        gc.set(GregorianCalendar.MINUTE, 0);
        gc.set(GregorianCalendar.SECOND, 0);
        return gc.getTime();
    }


    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public String getSysDate() {
        return sysDate;
    }

    public void setSysDate(String sysDate) {
        this.sysDate = sysDate;
    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public Date getKhjwhStartDate() {
        return khjwhStartDate;
    }

    public void setKhjwhStartDate(Date khjwhStartDate) {
        this.khjwhStartDate = khjwhStartDate;
    }

    public Date getKhjwhEndDate() {
        return khjwhEndDate;
    }

    public void setKhjwhEndDate(Date khjwhEndDate) {
        this.khjwhEndDate = khjwhEndDate;
    }

    public String getPmName() {
        return pmName;
    }

    public void setPmName(String pmName) {
        this.pmName = pmName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getKhj() {
        return khj;
    }

    public void setKhj(String khj) {
        this.khj = khj;
    }

    @Autowired
    public void setKhjwhService(KhjwhService khjwhService) {
        this.khjwhService = khjwhService;
    }


    @Autowired
    public void setPmDao(PmDao pmDao) {
        this.pmDao = pmDao;
    }

}
